package impl

import (
	pDomain "anubis-framework/pkg/domain"
	"anubis-framework/pkg/io"
	"gorm.io/gorm"
	"newton/internal/domain"
	"newton/internal/model"
	"newton/internal/vo"
)

type EnvironmentDaoImpl struct {
	db *gorm.DB
}

// 返回dao实现类
func GetEnvironmentDaoImpl() *EnvironmentDaoImpl {
	return &EnvironmentDaoImpl{domain.DataSource_.GormDb}
}

// 查找environment表的全部记录
func (_environmentDaoImpl *EnvironmentDaoImpl) FindAll() (*[]model.Environment, error) {
	io.Infoln("查找environment表的全部记录")

	var resultEnvironmentArray []model.Environment
	_environmentDaoImpl.db.Raw("select * from environment t").Scan(&resultEnvironmentArray)
	return &resultEnvironmentArray, nil
}

// 分页查找（模糊查询）
func (_environmentDaoImpl *EnvironmentDaoImpl) Page(pageVo *vo.PageVo) (*pDomain.Pager, error) {
	io.Infoln("分页查找environment表中的记录")

	var pager pDomain.Pager
	var resultEnvironmentArray []model.Environment
	var total int64
	_environmentDaoImpl.db.Model(&model.Environment{}).Count(&total)
	_environmentDaoImpl.db.Where("name LIKE ?", "%"+pageVo.Name+"%").Limit(pageVo.PageSize).Offset((pageVo.PageNo - 1) * pageVo.PageSize).Find(&resultEnvironmentArray)
	pager.List = &resultEnvironmentArray
	pager.Total = int(total)
	return &pager, nil
}

// 根据环境名称，模糊查询环境
func (_environmentDaoImpl *EnvironmentDaoImpl) FindByNameLike(name string) (*[]model.Environment, error) {
	io.Infoln("根据环境名称，模糊查询系统")

	var resultEnvironmentArray []model.Environment
	_environmentDaoImpl.db.Raw("select * from environment t where t.name like ?", "%"+name+"%").Scan(&resultEnvironmentArray)
	return &resultEnvironmentArray, nil
}

// 根据环境名称，精确查找环境
func (_environmentDaoImpl *EnvironmentDaoImpl) FindByName(name string) (*model.Environment, error) {
	io.Infoln("根据环境名称，精确查找环境")

	var resultEnvironment model.Environment
	_environmentDaoImpl.db.Raw("select * from environment t where t.name = ?", name).Scan(&resultEnvironment)
	return &resultEnvironment, nil
}

// 添加环境
func (_environmentDaoImpl *EnvironmentDaoImpl) Add(pageVo *vo.PageVo) (bool, error) {
	io.Infoln("添加环境")

	var environment model.Environment
	environment.Name = pageVo.Name
	_environmentDaoImpl.db.Model(&model.Environment{}).Create(&environment)
	return true, nil
}

// 根据id删除环境
func (_environmentDaoImpl *EnvironmentDaoImpl) DeleteById(id int) (bool, error) {
	io.Infoln("根据id删除环境")

	_environmentDaoImpl.db.Delete(&model.Environment{}, "id = ?", id)
	return true, nil
}

// 根据id修改环境
func (_environmentDaoImpl *EnvironmentDaoImpl) UpdateById(environment *model.Environment) (bool, error) {
	io.Infoln("根据id修改环境")

	_environmentDaoImpl.db.Model(&model.Environment{}).Where("id = ?", environment.Id).Update("name", environment.Name)
	return true, nil
}
